Not directly. But some other class which does have
a main()
method can use this class.
An object is a section of memory that contains variables and methods.
A class is a description of a possible object.
A class description is used when an object is created.
The new
operator is used with a constructor
to create an object.
class StringTester
{
public static void main ( String[] args )
{
String str1; // str1 is a reference to an object.
int len;
str1 = new String("Random Jottings"); // create an object of type String
len = str1.length(); // invoke the object's method length()
System.out.println("The string is " + len + " characters long");
}
}
A constructor has the same name as the class. The line from the above program
str1 = new String("Random Jottings");
creates a new object of type String
.
The new
operator
says to create a new object.
It is followed by the name of a constructor.
The constructor String()
is part of the definition for
the class String
.
Constructors often are used with values (called parameters) that are to be stored in the data part of the object that is created. In the above program, the characters "Random Jottings" (not including the quote marks) are stored in the new object.
There are usually several different constructors in a class, each with different parameters. Sometimes one is more convenient to use than another, depending on how the new object's data is to be initialized. However, all the constructors of a class follow the same plan in creating an object.
(Thought question:) Could a constructor be used a second time to change the values of an object it created?